<!--
 * @Author: pmy
 * @Date: 2021-09-02 14:39:12
 * @LastEditTime: 2022-11-25 09:57:21
 * @LastEditors: pmy
 * @Description: 行业竞品数据-table
 * @FilePath: \bdcar-net\src\components\table\baseTable.vue
 template
-->
<template>
  <div class="tablePage" v-loading="loading">
    <div class="search">

      <div class="header-query" v-for="v in queryInput" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-input clearable v-model="v.value" :placeholder="v.placeholder" class="search-input"
          @change="pagination.currentPage = 1;"
          @keyup.native.enter="pagination.currentPage = 1; getTableData()"></el-input>
      </div>

      <div class="header-query" v-for="v in querySelect" :key="v.prop" v-if="v.show">
        <span class="search-text">{{ v.name }}</span>

        <!-- 需要绑定修改粒度方法 -->
        <el-select v-model="v.value" :placeholder="v.placeholder" filterable class="search-input"
          @change="handleChangeTime">
          <el-option v-for="vv in optionList[v.prop]" :key="vv.value" :label="vv.label" :value="vv.value"> </el-option>
        </el-select>
      </div>

      <div class="header-query" v-for="v in queryCascader" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-cascader v-model="v.value" class="search-input" :placeholder="v.placeholder" :options="optionList[v.prop]"
          :props="cascaderSet" @change="pagination.currentPage = 1; getTableData()" :clearable="false"></el-cascader>
      </div>

      <div class="header-query" v-for="v in queryTime" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>

        <!-- <el-date-picker v-model="v.value" type="daterange" range-separator="至" :start-placeholder="v.placeholder[0]"
          :clearable="false" :end-placeholder="v.placeholder[1]" :picker-options="pickerOptions"
          class="search-input time-picker" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
        </el-date-picker> -->

        <!-- 粒度自定义type -->
        <el-date-picker v-model="v.value" align="right" :type="timeType" placeholder="选择日期" format="yyyy-MM-dd"
          class="search-input" value-format="yyyy-MM-dd" :picker-options="pickerOptions">
        </el-date-picker>

      </div>

      <div class="search-btn" @click="getTableData()" v-if="Btn.search">
        <div class="btn-img"></div>查询
      </div>
      <div class="add-btn" @click="handleClick(null, 'add')" v-if="Btn.add"
        v-show="btnPermissionSearch('basicData', 'fileManage', 'add')">
        <div class="btn-img"></div>新增
      </div>
      <div class="export-btn" @click="handleClick(null, 'export')" v-if="Btn.export" v-loading="exportLoading">
        <div class="btn-img"></div>
        {{ !exportLoading ? "导出" : "导出中" }}
      </div>
      <div class="deletes-btn" @click="handleClick(null, 'deletes')" v-if="Btn.deletes"
        v-show="btnPermissionSearch('basicData', 'fileManage', 'deletes')">
        批量删除
      </div>
    </div>
    <div class="base-table">
      <el-table highlight-current-row ref="myTable" :data="tableData" @selection-change="handleSelectionChange"
        height="100%" @sort-change="handleSortChange">
        <el-table-column :prop="v.prop" :label="v.name" v-for="v in tableItems" :key="v.prop" show-overflow-tooltip
          :sortable="v.sortable" :header-align="v.align ?? 'right'" :align="v.align ?? 'right'">

          <template slot="header">
            {{ v.name }}
            <el-tooltip class="item" effect="dark" placement="top" v-if="v.prop == '竞店GMV（卫生巾&私处护理市场）'">
              <div slot="content">
                天猫竞店GMV数据<br/>
                2024.04.29前来自生参平台，<br />
                2024.04.30~2024.07.19生参取消故爬空，<br />
                2024.07.20~2024.07.29为策略中心交易指数转化后数据，<br />
                2024.07.30~2024.08.07策略中心调整爬空，<br />
                2024.08.08起由于策略中心调整，该字段表示交易热度`
              </div>

              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>

          <template slot-scope="scope">
            <span v-if="scope.row[v.prop] !== ''">{{ scope.row[v.prop] }}</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination :page-size="pagination.pageSize" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="pagination.currentPage" :total="pagination.total"
        :page-sizes="[15, 50, 100, 300]" background layout="total,sizes, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 增删查改页面 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :visible="showDialog" width="56rem"
      :before-close="closeDialog">
      <template #title>
        <div class='dialog-title'>
          <div class="cicle"></div>
          {{ dialogTitle[showWhich] }}
        </div>
      </template>
      <div class="body" v-if="!!showDialog" v-loading="uploading">
        <el-form :model="updateInfo" :inline="true" ref="addformRef" :rules="addformRules">
          <el-form-item v-for="v in updateItems" :key="v.prop" :label="v.name" :prop="v.prop">
            <el-input v-model="updateInfo[v.prop]" :disabled="showWhich == 'detail' || v.disabled"
              v-if="v.type == 'input'"></el-input>
            <el-input type="textarea" v-else-if="v.type == 'textarea'" :autosize="{ minRows: 2 }" placeholder="请输入内容"
              :disabled="showWhich == 'detail'" style="width:38rem" v-model="updateInfo[v.prop]"></el-input>

            <el-date-picker v-model="updateInfo[v.prop]" type="datetime" placeholder="选择时间"
              value-format="yyyy-MM-dd HH:mm:ss" :disabled="showWhich == 'detail'" v-else-if="v.type == 'time'">
            </el-date-picker>

            <el-select v-model="updateInfo[v.prop]" filterable clearable :disabled="showWhich == 'detail'"
              v-else-if="v.type == 'select'">
              <el-option v-for="item in optionList[v.prop]" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>

            <treeSelect v-model="updateInfo[v.prop]" :data="optionList[v.prop]" v-else-if="v.type == 'cascader'"
              :disabled="showWhich == 'detail'" class="search-input"></treeSelect>

            <file-control ref="myFileControl" :fileHttp="ImportAPI" :getFileName="getFileName"
              :readOnly="showWhich == 'detail'" :downloadMethod="method.downloadMethod"
              :pFileList="updateInfo[v.prop] || []" :uploadMethod="method.uploadData"
              v-else-if="v.type == 'upload'"></file-control>

          </el-form-item>
        </el-form>
      </div>
      <div class="tool-bar">
        <div class="cancel-btn" @click="closeDialog">关闭</div>
        <div class="submit-btn" @click="handleSubmitFile" v-show="showWhich !== 'detail'">确定</div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import treeSelect from "@/components/common/treeSelect"
import { service } from "../../services/backServices"
import FileControl from '@/components/common/FileControl.vue';
import { export_json_to_excel } from "@/assets/js/FilExport";
import dayjs from "dayjs";
export default {
  props: [
    "query",//查询参数
    "updateItems",//增删查改的对象属性
    "optionList",//增删查改的对象属性的下拉select或者级联casual
    "Btn",//自定义btn功能
    "menuName",//权限-菜单名称
    "pageName",//权限-页面名称
  ],
  components: { treeSelect, FileControl },
  data() {
    return {
      //粒度tpye
      timeType: 'date',

      tableAllData: [],
      sortCol: "数据统计时间",
      orderCol: null,
      uploading: false,
      exportLoading: false,
      loading: false,
      method: {},
      //表格参数
      pagination: {
        total: 0,
        currentPage: 1,
        pageSize: 50,
      },
      multipleSelection: [],
      tableData: [],
      showWhich: "",
      updateInfo: {
        fileName: ''
      },
      params: {},
      cascaderSet: {
        value: 'value',
        emitPath: false,
        checkStrictly: false,
        expandTrigger: 'hover',
        multiple: false
      },
      addformRules: {
        fileName: [
          { required: true, message: '文件名称', trigger: 'blur' },
        ],
        fileAdd: [
          { required: true, message: '上传文件', trigger: 'blur' },
        ],
        uploadType: [
          { required: true, message: '上传类型', trigger: 'change' },
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近两天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          }
        ],
        disabledDate: (time) => {
          return time.getTime() > Date.now() - 8.64e7;
        },
      },
      dialogTitle: {
        add: "新增",
        edit: "编辑",
        detail: "详情"
      },
      showDialog: false,
      tableItems: [],
      methodParam: "getCompetingGmvData"
    };
  },
  computed: {
    queryInput() {
      let list = this.query.filter(v => {
        return v.type == "input"
      });
      return list;
    },
    querySelect() {
      let list = this.query.filter(v => {
        return v.type == "select"
      });
      return list;
    },
    queryCascader() {
      let list = this.query.filter(v => {
        return v.type == "cascader"
      });
      return list;
    },
    queryTime() {
      let list = this.query.filter(v => {
        return v.type == "time"
      });
      return list;
    },
    ImportAPI() {
      return GlobalSetting.IotConfig.ftpAPIService;
    },
  },
  created() {
    let _this = this;
    _this.method.addData = async function (model) {
      return service({
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: _this.methodParam + "/save",
        data: model,
      });
    };
    _this.method.editData = async function editTrashOverflowData(model) {
      return service({
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: _this.methodParam + "/update",
        data: model,
      });
    };
    _this.method.deleteData = async function (id) {
      let url = _this.methodParam + "/remove";
      return service({
        method: 'post',
        url: url,
        params: {
          id: id
        },
      });
    };
    _this.method.deleteDatas = async function (ids) {
      return service({
        method: 'post',
        url: _this.methodParam + "/batchRemove",
        params: {
          ids: ids
        },
        paramsSerializer: params => {
          return qs.stringify(params, {
            indices: false
          })
        }
      });
    };
    _this.method.uploadData = async function (data) {
      return service({
        headers: {
          'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryqs8javp5GsOgKvoQ'
        },
        method: 'post',
        url: _this.methodParam + "/upload",
        data: data,
        params: {
          uploadType: _this.updateInfo.uploadType
        }
      });
    };
    _this.method.downloadMethod = async function (url) {
      return service({
        method: 'post',
        url: _this.methodParam + "/download",
        responseType: 'blob',
        data: {
          url: url
        },
      });
    };
  },
  mounted() {
    this.getTableData();
  },
  methods: {
    getTableHead(query) {
      // 调用接口url修改
      if (query.platform == '天猫') {
        this.methodParam = "getCompetingGmvData"
      } else if (query.platform == '抖音') {
        this.methodParam = "getCompetingGmvDataDouyin"
      }

      // 表格字段修改
      if (query.platform == '天猫' && (query.unit == '日')) {
        this.tableItems = [
          // 
          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞店店铺名称", prop: "竞店店铺名称", align: "left", sortable: 'custom' },

          { name: "竞店GMV（卫生巾&私处护理市场）", prop: "竞店GMV（卫生巾&私处护理市场）", sortable: 'custom' },
          //天猫竞店GMV数据：
          // 2024.04.29前来自生参平台，
          // 2024.04.30~2024.07.19生参取消故爬空，
          // 2024.07.20~2024.07.29为策略中心交易指数转化后数据，
          // 2024.07.30~2024.08.07策略中心调整爬空，
          // 2024.08.08起由于策略中心调整，该字段表示交易热度

          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '天猫' && (query.unit == '月')) {
        this.tableItems = [

          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞店店铺名称", prop: "竞店店铺名称", align: "left", sortable: 'custom' },
          { name: "竞店GMV（卫生巾&私处护理市场）", prop: "竞店GMV（卫生巾&私处护理市场）", sortable: 'custom' },
          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '天猫' && (query.unit == '周')) {
        this.tableItems = [
          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞店店铺名称", prop: "竞店店铺名称", align: "left", sortable: 'custom' },
          { name: "竞店GMV（卫生巾&私处护理市场）", prop: "竞店GMV（卫生巾&私处护理市场）", sortable: 'custom' },
          { name: "前一周GMV", prop: "前一周GMV", sortable: 'custom' },
          { name: "GMV环比增长", prop: "GMV环比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '天猫' && (query.unit == '年')) {
        this.tableItems = [
          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞店店铺名称", prop: "竞店店铺名称", align: "left", sortable: 'custom' },
          { name: "竞店GMV（卫生巾&私处护理市场）", prop: "竞店GMV（卫生巾&私处护理市场）", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '天猫' && (query.unit == '自定义')) {
        this.tableItems = [
          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞店店铺名称", prop: "竞店店铺名称", align: "left", sortable: 'custom' },
          { name: "竞店GMV（卫生巾&私处护理市场）", prop: "竞店GMV（卫生巾&私处护理市场）", sortable: 'custom' },
          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '抖音' && (query.unit == '日')) {
        this.tableItems = [
          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞品品牌名称", prop: "竞品品牌名称", align: "left", sortable: 'custom' },
          { name: "竞品GMV", prop: "竞品GMV", sortable: 'custom' },
          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '抖音' && (query.unit == '月')) {
        this.tableItems = [

          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞品品牌名称", prop: "竞品品牌名称", align: "left", sortable: 'custom' },
          { name: "竞品GMV", prop: "竞品GMV", sortable: 'custom' },
          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom', sortable: 'custom' }
        ]
      } else if (query.platform == '抖音' && (query.unit == '周')) {
        this.tableItems = [

          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞品品牌名称", prop: "竞品品牌名称", align: "left", sortable: 'custom' },
          { name: "竞品GMV", prop: "竞品GMV", sortable: 'custom' },
          { name: "前一周GMV", prop: "前一周GMV", sortable: 'custom' },
          { name: "GMV环比增长", prop: "GMV环比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '抖音' && (query.unit == '年')) {
        this.tableItems = [

          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞品品牌名称", prop: "竞品品牌名称", align: "left", sortable: 'custom' },
          { name: "竞品GMV", prop: "竞品GMV", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom' }
        ]
      } else if (query.platform == '抖音' && (query.unit == '自定义')) {
        this.tableItems = [

          { name: "数据统计时间", prop: "数据统计时间", align: "left", sortable: 'custom' },
          { name: "竞品品牌名称", prop: "竞品品牌名称", align: "left", sortable: 'custom' },
          { name: "竞品GMV", prop: "竞品GMV", sortable: 'custom' },
          { name: "上一年同期GMV", prop: "上一年同期GMV", sortable: 'custom' },
          { name: "GMV同比增长", prop: "GMV同比增长", sortable: 'custom' },
          { name: "累计GMV", prop: "累计GMV", sortable: 'custom' },
          { name: "上一年同期累计GMV", prop: "上一年同期累计GMV", sortable: 'custom' },
          { name: "累计GMV同比增长", prop: "累计GMV同比增长", sortable: 'custom' },
          // { name: "数据记录数量", prop: "数据记录数量" },
          { name: "排名", prop: "排名", sortable: 'custom', sortable: 'custom' }
        ]
      }

    },
    setTableData() {
      this.tableData = this.tableAllData.slice(
        (this.pagination.currentPage - 1) * this.pagination.pageSize,
        this.pagination.currentPage * this.pagination.pageSize
      )

    },
    //表格参数改变触发
    handleSizeChange: function (val) {
      this.pagination.pageSize = val;
      this.setTableData();
    },
    handleCurrentChange: function (currentPage) {
      this.pagination.currentPage = currentPage;
      this.setTableData();
    },
    handleSortChange({ prop, order }) {
      this.sortCol = prop;
      this.orderCol = order;
      this.getTableData()
    },

    //修改粒度方法
    handleChangeTime(val) {
      debugger
      console.log(val)
      this.pagination.currentPage = 1;
      this.getTableData()

      let timeHash = {
        年: 'year',
        月: 'month',
        // 周: 'week',
        周: 'date',
        日: 'date',
      }

      this.timeType = timeHash[val]

      if (val == '抖音') {
        this.query.forEach(v => {
          if (v.prop == 'dataType') {
            v.show = false
          }
        })
      } else if (val == '天猫') {
        this.query.forEach(v => {
          if (v.prop == 'dataType') {
            v.show = true
          }
        })
      }
    },

    getTableData() {
      let _this = this, query = {}
      this.loading = true
      this.query.forEach(v => {
        this.params[v.prop] = v.value
        query[v.prop] = v.value
      })
      let myForm = new FormData()
      myForm.append('beginDate', query.beginDate)
      myForm.append('endDate', query.endDate)
      myForm.append('data_type', query.dataType)
      myForm.append('unit', query.unit)

      //#region 排序相关
      if (_this.sortCol != null) {
        myForm.append('sortBy', _this.sortCol)
      }
      if (_this.orderCol == 'ascending') {
        myForm.append('asc', 1)
      }
      //#endregion

      _this.getTableHead(query);
      let url = _this.methodParam;
      service({
        url: url,
        method: "post",
        data: myForm
      }).then(response => {
        this.loading = false
        if (response.data.code == 200) {
          this.tableAllData = response.data.data;
          this.setTableData();
          this.pagination.total = response.data.data.length;
          if (this.tableData.length == 0 && this.pagination.currentPage != 1) {
            this.pagination.currentPage = 1;
            this.getTableData();
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      val.forEach(v => {
        this.multipleSelection.push(v.id);
      })
    },
    getFileName(val) {
      let title = ''
      if (val && val.length > 0) {
        for (let i = 0; i < val.length - 1; i++) {
          title += val[i]
        }
      } else {
        title = ''
      }
      this.updateInfo.fileName = title
      this.$forceUpdate();
    },
    // 增删改查
    handleClick(row, obj) {
      if (this.uploading) {
        this.$message({
          message: '存在正在上传的文件，请等待数据上传成功再试',
          type: 'warning'
        });
        return
      }
      switch (obj) {
        case "add":
          this.updateInfo = {};
          this.showWhich = obj;
          this.showDialog = true
          this.$nextTick(() => {
            this.$refs.addformRef.clearValidate();
          })
          break;
        case "edit":
          this.updateInfo = JSON.parse(JSON.stringify(row));
          this.showWhich = obj;
          this.showDialog = true
          this.$nextTick(() => {
            this.$refs.addformRef.clearValidate();
          })
          break;
        case "detail":
          this.updateInfo = JSON.parse(JSON.stringify(row));
          this.showWhich = obj;
          this.showDialog = true
          break;
        case "delete":
          this.deleteData(row.id);
          break;
        case "deleteMany":
          this.deleteManyData();
          break;
        case "export":
          this.exportTable();
          break;
        default:
          break;
      }
    },
    handleSubmitFile() {
      if (!this.updateInfo.uploadType && this.updateInfo.uploadType != 0) {
        this.$message({
          message: '上传类型不能为空',
          type: 'warning'
        });
        return
      }
      this.handleSubmit();
      // this.$refs.addformRef.validate((valid) => {
      //   if (valid) {
      //     this.handleSubmit();
      //   }
      // })
    },
    //提交事件
    async handleSubmit() {
      let _this = this;
      const fileDom = this.$refs.myFileControl
      if (fileDom && fileDom[0]) {
        this.uploading = true
        let fileList = await fileDom[0].uploadInfo(), propName = 'file'
        this.uploading = false
        if (!!fileList) {
          _this.updateInfo[propName + 'AddStr'] = JSON.stringify(fileList);   //去掉最后一个逗号避免后端报错，再加上中括号构造json字符串          
          _this.updateInfo['fileName'] = fileList[0].name;    //从上传的文件中读取文件名
        }
        if (fileDom[0]?.delFileList?.length > 0) {       // 将删除的图片由数组转为字符串拼接
          _this.updateInfo[propName + 'DelStr'] = JSON.stringify(fileDom[0].delFileList)
        }
      }
      if (!_this.updateInfo.fileName) {
        this.$message({
          message: '文件不能为空',
          type: 'warning'
        });
        return
      }
      switch (this.showWhich) {
        case 'add':
          this.addInfo();
          break;
        case 'edit':
          this.editInfo();
          break;
      }
    },
    addInfo() {
      let _this = this;
      this.method.addData(_this.updateInfo).then(function (response) {
        if (response.data.code == 0) {
          _this.getTableData();
          _this.showWhich = "";
          _this.showDialog = false
          _this.$notify({
            message: "信息保存成功！",
            type: "success",
            position: "bottom-right",
            duration: 2000,
          });
        }
      }).catch(function (error) {
        _this.$notify({
          message: "信息保存失败！",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
        console.log(error)
      });
    },
    editInfo() {
      let _this = this;
      this.method.editData(_this.updateInfo).then(function (response) {
        if (response.data.code == 0) {
          _this.getTableData();
          _this.showWhich = "";
          _this.showDialog = false
          _this.$notify({
            message: "信息保存成功！",
            type: "success",
            position: "bottom-right",
            duration: 2000,
          });
        }
      }).catch(function (error) {
        _this.$notify({
          message: "信息保存失败！",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
        console.log(error)
      });
    },
    deleteData(id) {
      this.$confirm("此操作将删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let _this = this;
        _this.method.deleteData(id).then(function (response) {
          if (response.data.code == 0) {
            _this.getTableData();
            _this.showWhich = "";
            _this.showDialog = false
            _this.$notify({
              message: "信息删除成功！",
              type: "success",
              position: "bottom-right",
              duration: 2000,
            });
          }
        })
      })
    },
    deleteManyData() {
      let _this = this;
      if (_this.multipleSelection.length > 0) {
        _this.$confirm("此操作将删除该项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          _this.method.deleteDatas(_this.multipleSelection).then(function (response) {
            if (response.data.code == 0) {
              _this.getTableData();
              _this.showWhich = "";
              _this.showDialog = false
              _this.$notify({
                message: "信息删除成功！",
                type: "success",
                position: "bottom-right",
                duration: 2000,
              });
            }
          })
        })
      } else {
        this.$notify({
          message: "请至少选择一项",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
      }
    },
    closeDialog() {
      this.showDialog = false
    },
    exportTable() {
      this.exportLoading = true;
      let _this = this;

      if (this.tableAllData.length <= 0) {
        _this.$notify({
          message: "当前数据为空",
          type: "error",
          position: "bottom-right",
          duration: 1000,
        });
        this.exportLoading = false;
        return;
      }
      let filename = "" + dayjs().format("YYYY-MM-DD HH:ss:mm");
      let multiHeader = []; //标题设置
      let tHeader = [], filterVal = [];

      _this.tableItems.forEach(v => {
        tHeader.push(v.name);
        filterVal.push(v.prop);
      })
      let jsonData = this.tableAllData;
      let merges = []; // 合并单元格
      export_json_to_excel({
        multiHeader,
        header: tHeader,
        merges,
        filterVal,
        jsonData,
        filename: filename,
        autoWidth: 30,
        bookType: "xlsx",
      });
      this.exportLoading = false;
    },
  },

  activated() {
    let _this = this;
    _this.$nextTick(() => {
      _this.$refs.myTable.doLayout();
    })
  }
}
</script>

<style lang="less" scoped>
.search {
  .search-input {
    width: 160px;
  }
}

.search2 {
  height: 130px;
}

.baseTable2 {
  top: 110px;
}
</style>